package com.zzl.study.auth.domain.converter;

import com.zzl.study.auth.domain.ClientSettings;
import com.zzl.study.auth.domain.RegisteredClient;
import com.zzl.study.auth.domain.TokenSettings;
import com.zzl.study.auth.domain.dto.RegisteredClientDto;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;

/**
 * @author: zhangzl
 * @date: 2023/12/8 9:58
 * @version: 1.0
 * @description: 注册客户端转换器
 */
@Component
public class RegisteredClientConverter implements Converter<RegisteredClientDto, RegisteredClient> {

    @Override
    public RegisteredClient convert(@NonNull RegisteredClientDto source) {
        RegisteredClient registeredClient = new RegisteredClient();
        registeredClient.setId(source.getId());
        registeredClient.setClientId(source.getClientId());
        registeredClient.setClientIdIssuedAt(source.getClientIdIssuedAt() == null ? null : new Timestamp(source.getClientIdIssuedAt().getTime()));
        registeredClient.setClientSecret(source.getClientSecret());
        registeredClient.setClientSecretExpiresAt(source.getClientSecretExpiresAt() == null ? null : new Timestamp(source.getClientSecretExpiresAt().getTime()));
        registeredClient.setClientName(source.getClientName());
        registeredClient.setClientAuthenticationMethods(CollectionUtils.isEmpty(source.getClientAuthenticationMethods()) ? null : String.join(",", source.getClientAuthenticationMethods()));
        registeredClient.setAuthorizationGrantTypes(CollectionUtils.isEmpty(source.getAuthorizationGrantTypes()) ? null : String.join(",", source.getAuthorizationGrantTypes()));
        registeredClient.setRedirectUris(CollectionUtils.isEmpty(source.getRedirectUris()) ? null : String.join(",", source.getRedirectUris()));
        registeredClient.setPostLogoutRedirectUris(CollectionUtils.isEmpty(source.getPostLogoutRedirectUris()) ? null : String.join(",", source.getPostLogoutRedirectUris()));
        registeredClient.setScopes(CollectionUtils.isEmpty(source.getScopes()) ? null : String.join(",", source.getScopes()));
        registeredClient.setClientSettings(new ClientSettings().toString());
        if (source.getTokenSettings() != null) {
            TokenSettings tokenSettings = new TokenSettings();
            tokenSettings.setAuthorizationCodeTimeToLive(source.getTokenSettings().getAuthorizationCodeTimeToLive());
            tokenSettings.setAccessTokenTimeToLive(source.getTokenSettings().getAccessTokenTimeToLive());
            tokenSettings.setRefreshTokenTimeToLive(source.getTokenSettings().getRefreshTokenTimeToLive());
            registeredClient.setTokenSettings(tokenSettings.toString());
        }
        return registeredClient;
    }

}
